<template>
  <div class="modal-overlay" @click.self="$emit('close')">
    <div class="modal-content large">
      <div class="modal-header">
        <h3>选择排班警员</h3>
        <button class="close-btn" @click="$emit('close')">×</button>
      </div>
      <div class="modal-body">
        <div class="table-container">
          <table>
            <thead>
            <tr>
              <th class="checkbox-col"><input type="checkbox" @change="toggleSelectAll" :checked="isAllSelected" title="全选/全不选"></th>
              <th>警员编号</th>
              <th>姓名</th>
              <th>部门</th>
              <th>联系方式</th>
              <th>专业技能</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="officer in policeList" :key="officer.id" @click="toggleSelection(officer)" class="selectable-row">
              <td class="checkbox-col" @click.stop>
                <input type="checkbox" :value="officer" v-model="selectedOfficers">
              </td>
              <td>{{ officer.officerNumber }}</td>
              <td>{{ officer.name }}</td>
              <td>{{ officer.department }}</td>
              <td>{{ officer.phone }}</td>
              <td>{{ officer.skills }}</td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-cancel" @click="$emit('close')">取消</button>
        <button class="btn btn-confirm" @click="confirmSelection">确定选择</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';

const props = defineProps<{
  policeList: any[],
  initialSelection: any[]
}>();
const emit = defineEmits(['close', 'confirm']);

// 深拷贝初始选中项，避免直接修改父组件数据
const selectedOfficers = ref(JSON.parse(JSON.stringify(props.initialSelection || [])));

const confirmSelection = () => {
  emit('confirm', selectedOfficers.value);
};

// 全选/反选逻辑
const isAllSelected = computed(() => {
  return props.policeList.length > 0 && selectedOfficers.value.length === props.policeList.length;
});

const toggleSelectAll = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.checked) {
    selectedOfficers.value = JSON.parse(JSON.stringify(props.policeList));
  } else {
    selectedOfficers.value = [];
  }
};

// 点击行也能选中
const toggleSelection = (officer: any) => {
  const index = selectedOfficers.value.findIndex(o => o.id === officer.id);
  if (index > -1) {
    selectedOfficers.value.splice(index, 1);
  } else {
    selectedOfficers.value.push(JSON.parse(JSON.stringify(officer)));
  }
};
</script>

<style scoped>
@import "@/assets/styles/views/admin/OfficerSelectionModal.css";
</style>
